<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useConfigStore } from '@/stores/modules/config'

const videoRef = ref<HTMLVideoElement>()
const { baseURL, videoBvid } = useConfigStore()
const isMuted = ref(true)

onMounted(startPlayVideo)

/** 根据配置文件的bv号顺序播放视频 */
function startPlayVideo() {
  const localKey = 'currentBv'
  let currentBv = videoBvid[0]

  const localBv = localStorage.getItem(localKey)
  if (localBv) {
    let bvIndex = videoBvid.findIndex((f) => f === localBv) + 1
    if (bvIndex > videoBvid.length - 1) {
      bvIndex = 0
    }
    currentBv = videoBvid[bvIndex]
  }

  videoPlay(currentBv)
  localStorage.setItem(localKey, currentBv)
}

/** 获取bv视频播放地址 */
async function getUrl(bvid: string) {
  try {
    const {
      data: { data },
    } = await axios({
      baseURL,
      url: 'video',
      method: 'get',
      params: { bvid },
    })
    return data.url as string
  } catch (e) {
    console.error(e)
    return null
  }
}

/** 播放视频 */
async function videoPlay(bvid: string) {
  const url = await getUrl(bvid)
  const video = videoRef.value
  if (url && video) {
    video.src = url
    video.muted = isMuted.value
    video.play()
  }
}

/** 切换静音 */
function switchMuted(value: boolean) {
  const video = videoRef.value
  if (video) {
    video.muted = value
  }
}

/** 只有onvolumechange才能获取真实的muted值 */
function volumechange(payload: Event) {
  const video = payload.target as HTMLVideoElement
  isMuted.value = video.muted
}

defineExpose({ switchMuted })
</script>

<template>
  <video ref="videoRef" @volumechange="volumechange" @ended="startPlayVideo"></video>
</template>

<style lang="less" scoped>
video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  pointer-events: none;
}
</style>
